package com.jianbo.proxy.entity;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

import org.smartboot.http.common.enums.HttpStatus;
import org.smartboot.http.server.HttpResponse;

public class HttpResponseMiddle {

    HttpStatus httpStatus;
    byte[] responseBytes;
    Map<String, String> headerMap;
    private String contentType;

    public HttpStatus getHttpStatus() {
        return this.httpStatus;
    }


    public byte[] getResponseBytes() {
        return this.responseBytes;
    }

    public void setResponseBytes(byte[] responseBytes) {
        this.responseBytes = responseBytes;
    }

    public Map<String,String> getHeaderMap() {
        return this.headerMap;
    }

    public void setHeaderMap(Map<String,String> headerMap) {
        this.headerMap = headerMap;
    }

    public String getContentType() {
        return this.contentType;
    }

    public HttpResponseMiddle() {
        headerMap = new LinkedHashMap<>();
    }

    public void setHttpStatus(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }

    public void setHeader(String key, String value) {
        headerMap.put(key, value);
    }

    public void write(byte[] responseBytes) {
        this.responseBytes = responseBytes;
    }

    public void write(String responseStr) {
        this.responseBytes = responseStr.getBytes(Charset.forName("utf-8"));
    }

    public byte[] read() {
        return this.responseBytes;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public void flush(HttpResponse response) throws IOException {
        if(contentType != null) {
            response.setContentType(contentType);
        }
        if(httpStatus != null) {
            response.setHttpStatus(httpStatus);
        }
        for(String key : headerMap.keySet()) {
            String value = headerMap.get(key);
            // Debug.info(key +" "+ headerMap.get(key));
            if(value.equals(response.getHeader(key))
                || "Transfer-Encoding".equals(key) || "Date".equals(key)) {
                //
            } else {
                response.setHeader(key, headerMap.get(key));
            }
        }
        
        // 实际上设计了长度后前端拿不到数据！！！
        // 是否需要设计长度
        // response.setContentLength(responseBytes.length);

        if(responseBytes == null) {
            throw new RuntimeException("response Bytes is null");
        }
        
        response.getOutputStream().write(responseBytes);
        response.getOutputStream().flush();
        response.close();
    }
    
}
